package com.swxy.club.utils;

import cn.hutool.core.lang.Assert;
import com.swxy.club.dto.bo.CurrentUserBO;
import com.swxy.club.dto.vo.CurrentUserVO;
import com.swxy.club.enums.Gender;

import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 易
 */
public class SessionUtil {

    public static CurrentUserVO  getCurrentUser(HttpSession session) {
        // 从 session 中获取用户对象
        Object userObject = session.getAttribute("user_session");

        // 检查是否为 null
        Assert.notNull(userObject, "用户未登录");

        // 如果是 LinkedHashMap，则手动转换为 User
        if (userObject instanceof LinkedHashMap) {
            @SuppressWarnings("unchecked")
            LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) userObject;

            CurrentUserVO user = new CurrentUserVO();
            user.setId(((Integer) map.get("id")).longValue());
            user.setIdNumber((String) map.get("idNumber"));
            user.setRealName((String) map.get("realName"));
            user.setEmail((String) map.get("email"));
            user.setPhone((String) map.get("phone"));
            user.setGender(Gender.valueOf(((String) map.get("gender")).toUpperCase()));
            user.setAvatar((String) map.get("avatar"));
            return user;
        }
        // 如果是 User 类型，直接返回
        if (userObject instanceof CurrentUserVO) {
            return (CurrentUserVO) userObject;
        }
        throw new IllegalArgumentException("Session 中的用户数据类型不正确");
    }


    public static CurrentUserBO getCurrentUser(String token) {
        Map<String, String> payload = JWTUtil.getPayload(token);
        CurrentUserBO user = new CurrentUserBO();
        user.setId(Long.parseLong(payload.get("id")));
        user.setIdNumber(payload.get("idNumber"));
        user.setRealName(payload.get("name"));
        return user;
    }

}
